﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace ImgThumb.UI
{
    public partial class ReName : Form
    {
        private string[] _files;//选择文件的集合
        private FileInfo _fi;//创建一个FileInfo对象，用于获取文件信息
        private string[] _lvFiles = new string[7];//向控件中添加的行信息
        private Thread _tWork;//处理批量更名方法的线程
        private bool _useTemplate = false;//判断是否应用了模板
        private bool _wFlag = true;//窗体是否在最前

        public ReName()
        {
            InitializeComponent();
        }

        private void ReName_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
        }

        private void 添加文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                lv_Files.GridLines = true;
                lv_Files.Items.Clear();
                _files = openFileDialog1.FileNames;
                AddFile();
            }
        }

        private void 总在最前ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_wFlag)
            {
                总在最前ToolStripMenuItem.Checked = true;
                this.TopMost = true;
                _wFlag = false;
            }
            else
            {
                总在最前ToolStripMenuItem.Checked = false;
                this.TopMost = false;
                _wFlag = true;
            }
        }

        private void 导出文件列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw;
                string txt = "";
                string path = saveFileDialog1.FileName;
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    txt = lv_Files.Items[i].SubItems[0].Text + "  " + lv_Files.Items[i].SubItems[1].Text;
                    sw = File.AppendText(path);
                    sw.WriteLine(txt);
                    sw.Close();
                }
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 更名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    lv_Files.Items[i].SubItems[6].Text = "";
                }
                tsslError.Text = "";
                _tWork = new Thread(new ThreadStart(ChangeName));
                _tWork.Start();
            }
        }

        private static string TraditionalChineseToSimpli_fiedChinese(string str)//繁体转简体
        {
            return (Microsoft.VisualBasic.Strings.StrConv(str, Microsoft.VisualBasic.VbStrConv.SimplifiedChinese, 0));
        }

        private static string Simpli_fiedChineseToTraditionalChinese(string str)//简体转繁体
        {
            return (Microsoft.VisualBasic.Strings.StrConv(str as string, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0));
        }

        private void 繁体转简体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    string name = lv_Files.Items[i].SubItems[1].Text;
                    string name1 = TraditionalChineseToSimpli_fiedChinese(name);
                    lv_Files.Items[i].SubItems[1].Text = name1;
                }
            }
        }

        private void 简体转繁体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    string name = lv_Files.Items[i].SubItems[1].Text;
                    string name1 = Simpli_fiedChineseToTraditionalChinese(name);
                    lv_Files.Items[i].SubItems[1].Text = name1;
                }
            }
        }
        //模板
        private void txtTemplate_TextChanged(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                if (_useTemplate && txtTemplate.Text.Trim() != "" && ccb_Template.Text != "")
                {

                    for (int i = 0; i < lv_Files.Items.Count; i++)
                    {
                        string name = lv_Files.Items[i].SubItems[1].Text;
                        string name1 = name.Remove(name.LastIndexOf("_") + 1);
                        string newName = name.Replace(name1, txtTemplate.Text.Trim() + "_");
                        lv_Files.Items[i].SubItems[1].Text = newName;
                    }
                }
            }
        }

        private void nuStart_ValueChanged(object sender, EventArgs e)
        {
            StartNumAndAdd();
        }

        private void nuAdd_ValueChanged(object sender, EventArgs e)
        {
            StartNumAndAdd();
        }

        #region 拖拽操作

        private void lv_Files_DragDrop(object sender, DragEventArgs e)
        {
            _files = ((string[])e.Data.GetData(DataFormats.FileDrop));
            AddFile();
        }

        private void lv_Files_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }
        #endregion

        //文件名选项
        private void cbb_FileOptions_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type = this.cbb_FileOptions.SelectedItem.ToString().Trim();
            if (lv_Files.Items.Count > 0)
            {
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    string name = lv_Files.Items[i].SubItems[1].Text;
                    string tem = name.Remove(name.LastIndexOf("."));
                    switch (type)
                    {
                        case "不改变":

                            break;
                        case "文件名大写":
                            lv_Files.Items[i].SubItems[1].Text = name.Replace(tem, tem.ToUpper());
                            break;
                        case "文件名小写":
                            lv_Files.Items[i].SubItems[1].Text = name.Replace(tem, tem.ToLower());
                            break;
                        case "首字母大写":
                            lv_Files.Items[i].SubItems[1].Text = name.Substring(0, 1).ToUpper() + name.Substring(1);
                            break;
                        case "扩展名大写":
                            tem = name.Substring(name.LastIndexOf("."), name.Length - name.LastIndexOf("."));
                            lv_Files.Items[i].SubItems[1].Text = name.Replace(tem, tem.ToUpper());
                            break;
                        case "扩展名小写":
                            tem = name.Substring(name.LastIndexOf("."), name.Length - name.LastIndexOf("."));
                            lv_Files.Items[i].SubItems[1].Text = name.Replace(tem, tem.ToLower());
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        //预设模板
        private void ccb_Template_SelectedIndexChanged(object sender, EventArgs e)
        {
            int k = (int)nuStart.Value;
            if (ccb_Template.Text != "")
            {
                txtTemplate.Text = ccb_Template.Text.Remove(ccb_Template.Text.LastIndexOf("_"));
                int B = ccb_Template.SelectedIndex;
                switch (B)
                {
                    case 0:
                        if (lv_Files.Items.Count > 0)
                        {
                            for (int i = 0; i < lv_Files.Items.Count; i++)
                            {
                                string name = lv_Files.Items[i].SubItems[1].Text;
                                string name1 = name.Remove(name.LastIndexOf("."));
                                string name2 = "pic_" + k.ToString();
                                k = k + (int)nuAdd.Value;
                                string newName = name.Replace(name1, name2);
                                lv_Files.Items[i].SubItems[1].Text = newName;
                            }
                            _useTemplate = true;
                        }
                        break;
                    case 1:
                        if (lv_Files.Items.Count > 0)
                        {
                            for (int i = 0; i < lv_Files.Items.Count; i++)
                            {
                                string name = lv_Files.Items[i].SubItems[1].Text;
                                string name1 = name.Remove(name.LastIndexOf("."));
                                string name2 = "_file_" + k.ToString();
                                k = k + (int)nuAdd.Value;
                                string newName = name.Replace(name1, name2);
                                lv_Files.Items[i].SubItems[1].Text = newName;
                            }
                            _useTemplate = true;
                        }
                        break;
                }
            }
        }

        #region 私有方法

        private void StartNumAndAdd()//设置起始数字和增量值
        {
            int k = (int)nuStart.Value;
            if (ccb_Template.Text != "")
            {
                if (lv_Files.Items.Count > 0)
                {
                    for (int i = 0; i < lv_Files.Items.Count; i++)
                    {
                        string name = lv_Files.Items[i].SubItems[1].Text;
                        string name1 = name.Remove(name.LastIndexOf("."));
                        string name2 = name1.Remove(name.LastIndexOf("_") + 1) + k.ToString();
                        k = k + (int)nuAdd.Value;
                        string newName = name.Replace(name1, name2);
                        lv_Files.Items[i].SubItems[1].Text = newName;
                    }
                    _useTemplate = true;
                }
            }
        }

        private void ChangeName()
        {
            int error = 0;
            try
            {
                tspPrg.Minimum = 0;
                tspPrg.Maximum = lv_Files.Items.Count - 1;
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    string path = lv_Files.Items[i].SubItems[4].Text;
                    string sourcePath = path + lv_Files.Items[i].SubItems[0].Text;
                    if (!File.Exists(sourcePath))
                    {
                        continue;
                    }
                    string newPath = path + lv_Files.Items[i].SubItems[1].Text;
                    if (File.Exists(newPath))
                    {
                        if (MessageBox.Show("文件已存在，是否覆盖？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {
                            File.Delete(newPath);
                        }
                        else
                        {
                            newPath = "复件 " + newPath;
                        }
                    }
                    File.Copy(sourcePath, newPath);
                    File.Delete(sourcePath);
                    tspPrg.Value = i;
                    lv_Files.Items[i].SubItems[0].Text = lv_Files.Items[i].SubItems[1].Text;
                    lv_Files.Items[i].SubItems[6].Text = "√成功";
                }
            }
            catch (Exception ex)
            {
                error++;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                tsslError.Text = error.ToString() + " 个错误";
            }
        }
        /// <summary>
        /// 添加文件
        /// </summary>
        private void AddFile()
        {
            if (_files == null || _files.Length == 0)
            {
                return;
            }
            for (int i = 0; i < _files.Length; i++)
            {
                string path = _files[i].ToString();
                if (!File.Exists(path))
                {
                    continue;
                }
                _fi = new FileInfo(path);
                string name = path.Substring(path.LastIndexOf("\\") + 1, path.Length - 1 - path.LastIndexOf("\\"));
                string ftype = path.Substring(path.LastIndexOf("."), path.Length - path.LastIndexOf("."));
                string createTime = _fi.CreationTime.ToShortDateString();
                double a = Convert.ToDouble(Convert.ToDouble(_fi.Length) / Convert.ToDouble(1024));
                string fsize = a.ToString("0.0") + " KB";
                _lvFiles[0] = name;
                _lvFiles[1] = name;
                _lvFiles[2] = ftype;
                _lvFiles[3] = createTime;
                _lvFiles[4] = path.Remove(path.LastIndexOf("\\") + 1);
                _lvFiles[5] = fsize;

                ListViewItem lvi = new ListViewItem(_lvFiles);
                lvi.UseItemStyleForSubItems = false;
                lvi.SubItems[1].BackColor = Color.AliceBlue;

                lv_Files.Items.Add(lvi);
            }
            tsslSum.Text = lv_Files.Items.Count.ToString();
        }

        #endregion

        int preNameLen = 0;//文件名前添加字符长度
        int backNameLen = 0;//文件名后添加字符长度
        //文件名前添加
        private void txt_PreFileName_TextChanged(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                string tem = this.txt_PreFileName.Text.Trim();
                string path = "";

                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    path = lv_Files.Items[i].SubItems[1].Text;
                    if (preNameLen > tem.Length)
                    {
                        if (tem.Length == 0)
                        {
                            lv_Files.Items[i].SubItems[1].Text = path.Substring(1);
                        }
                        else
                        {
                            lv_Files.Items[i].SubItems[1].Text = path.Substring(0, tem.Length - 1) + path.Substring(tem.Length);
                        }
                    }
                    else
                    {
                        lv_Files.Items[i].SubItems[1].Text = tem.Substring(tem.Length - 1) + path;
                    }
                }
                preNameLen = this.txt_PreFileName.Text.Trim().Length;
            }
        }
        //文件名后添加
        private void txt_BackFileName_TextChanged(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                string tem = this.txt_BackFileName.Text.Trim();
                string name = "";
                string prefix = "";

                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    name = lv_Files.Items[i].SubItems[1].Text;
                    prefix = name.Substring(name.LastIndexOf("."));
                    if (backNameLen > tem.Length)
                    {
                        name = name.Replace(prefix, "");
                        lv_Files.Items[i].SubItems[1].Text = name.Substring(0, name.Length - 1) + prefix;
                    }
                    else
                    {
                        lv_Files.Items[i].SubItems[1].Text = name.Replace(prefix, "") + tem.Substring(tem.Length - 1) + prefix;
                    }
                }
                backNameLen = this.txt_BackFileName.Text.Trim().Length;
            }
        }
        //文件名中删除
        private void txt_Drop_TextChanged(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    try
                    {
                        string name = lv_Files.Items[i].SubItems[1].Text;
                        if (name.Contains(this.txt_Drop.Text.Trim()))
                        {
                            name = name.Replace(this.txt_Drop.Text.Trim(), "");
                        }
                        else
                        {
                            //特殊符号转义
                            name = Regex.Replace(name, this.txt_Drop.Text.Trim().Replace(@"\", @"\\").Replace(".", @"\."), "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        }

                        //name = Regex.Replace(name.Substring(0, name.LastIndexOf(".")), this.txt_Drop.Text.Trim(), "") + name.Substring(name.LastIndexOf("."));

                        lv_Files.Items[i].SubItems[1].Text = (name.StartsWith(".")) ? "未命名" + name : name;
                    }
                    catch (Exception)
                    {

                    }
                }
            }

        }
        //更改扩展名
        private void txt_Prefix_TextChanged(object sender, EventArgs e)
        {
            if (lv_Files.Items.Count > 0)
            {
                string name = "";
                string tem = "";
                string prefix = "";
                for (int i = 0; i < lv_Files.Items.Count; i++)
                {
                    name = lv_Files.Items[i].SubItems[1].Text;
                    tem = name.Substring(name.LastIndexOf("."));
                    prefix = this.txt_Prefix.Text.Trim().StartsWith(".") ? this.txt_Prefix.Text.Trim() : "." + this.txt_Prefix.Text.Trim();
                    lv_Files.Items[i].SubItems[1].Text = name.Replace(tem, prefix);
                    lv_Files.Items[i].SubItems[2].Text = prefix;
                }
            }
        }
    }
}
